<?php
/**
 * @version		$Id: categories.php
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die;
jimport('joomla.application.component.model');

class PromotionsModelRedemptions extends JModelLegacy
{
	protected $_extension = 'com_promotions';
	private $_parent = null;
	private $_items = null;
	private $_limit = null;
	private $_limitstart = null;

	function __construct(){
	
		parent::__construct();
		$mainframe = JFactory::getApplication();
		
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$layout = JRequest::getCmd('layout');
		$cid = JRequest::getCmd('id');
		
		$this->_limit = $mainframe->getUserStateFromRequest( $context.$view.$layout.$cid.'limit', 'limit', 9, 9);
		$this->_limitstart = $mainframe->getUserStateFromRequest( $context.$view.$layout.$cid.'limitstart', 'limitstart', 0 );

	}
	
	public function addPoint($userID=null, $promID=null){
		//echo 'call function Addpoint';
		return;
		
		if($promID >0){
			$db		= $this->getDbo();
			
			// Get the promotion user.
			$query	= $db->getQuery(true);
			$query->select('*');
			$query->from('`#__wrd_point`');
			$query->where('`user_id` = '.$db->Quote($userID)." AND type=4 AND transaction=".$db->Quote($promID)." AND created_date='".date('Y-m-d')."'");
			$db->setQuery((string) $query);
			$promUser = $db->loadObject();
			
			if(empty($promUser)){
				//Get point of Promotions
				$query	= $db->getQuery(true);
				$query->select('point');
				$query->from('`#__wrd_promotions`');
				$query->where('id='.$promID);
				$db->setQuery((string) $query);
				$promInfo = $db->loadObject();
				
				$sqlQuery = sprintf("INSERT INTO #__wrd_point (user_id, type, created_date, point, remain, transaction,flagConvert) VALUES (%s, 4, NOW(), %s, %s, %s,1)", $db->Quote($userID), $promInfo->point, $promInfo->point, $db->Quote($promID));
				$addPointQuery = $db->setQuery($sqlQuery);
				$addPointQuery->query();
				echo("You (".$userID.") have ".$promInfo->point." points.");
				
				$sqlQuery = sprintf("UPDATE #__wrd_promotions SET clicks=clicks+1 WHERE id=%s", $db->Quote($promID));
				$updateClickPromo = $db->setQuery($sqlQuery);
				$updateClickPromo->query();
			}
		}
	}
	
	/**
	 * redefine the function an add some properties to make the styling more easy
	 * @return mixed An array of data items on success, false on failure.
	 */
	public function getItems()
	{
        // Initialise variables.
        $db        = $this->getDbo();
        $query    = $db->getQuery(true);
        
        $query = "
            SELECT
                `f`.NAME       AS `image`,
                `t`.*
            FROM #__wrd_products `t`
                LEFT JOIN #__wrd_file `f`
                  ON `f`.TYPE = 'image'
                    AND `t`.id = `f`.product_id
            WHERE `t`.published = 1
                  AND `t`.quantity > 0
                  AND `t`.cat_id = ".intval($_GET['id'])."
                  AND ((YEAR(`t`.published_up) = 0)
                       AND (YEAR(`t`.published_down) = 0)
                        OR ('".date('Y-m-d')."' BETWEEN DATE(`t`.published_up)
                            AND DATE(`t`.published_down)))
            GROUP BY `t`.cat_id
            ORDER BY `t`.id DESC
        ";
          
        $db->setQuery($query, $this->_limitstart, $this->_limit);
        $this->_items = $db->loadObjectList();
        
		return $this->_items;
	}
    
    /**
     * redefine the function an add some properties to make the styling more easy
     * @return mixed An array of data items on success, false on failure.
     */
    public function getItemsShop(){
    	
        // Initialise variables.
        $db        = $this->getDbo();
        $query    = $db->getQuery(true);
        $id = JRequest::getVar('id');
        $user = &JFactory::getUser();
        
        if($id == 'recommend'){
        	$user_point = $_SESSION[$user->id.'p'];
        	
        	$query = "
	            SELECT
	                `f`.NAME       AS `image`,
	                `t`.*
	            FROM #__wrd_products `t`
	                LEFT JOIN #__wrd_file `f`
	                  ON `f`.TYPE = 'image2'
	                    AND `t`.id = `f`.product_id
	            WHERE `t`.published = 1
	                  AND `t`.quantity >= 0
	                  AND ((point <= ".$user_point." AND point > 0) OR (pointx <= ".$user_point." AND pointx > 0))
	            GROUP BY `t`.id
	            ORDER BY `t`.id DESC
	        ";
			
			//echo $query;
        }
        else{
        	if($id != 0 ){
        		$query = "
	            SELECT
	                `f`.NAME       AS `image`,
	                `t`.*
	            FROM #__wrd_products `t`
	                LEFT JOIN #__wrd_file `f`
	                  ON `f`.TYPE = 'image2'
	                    AND `t`.id = `f`.product_id
	            WHERE `t`.published = 1
	                  AND `t`.quantity >= 0
	                  AND `t`.cat_id = ".intval($_GET['id'])."
	            GROUP BY `t`.id
	            ORDER BY `t`.id DESC
	        ";
        	}else{
        		$query = "
	            SELECT
	                `f`.NAME       AS `image`,
	                `t`.*
	            FROM #__wrd_products `t`
	                LEFT JOIN #__wrd_file `f`
	                  ON `f`.TYPE = 'image2'
	                    AND `t`.id = `f`.product_id
	            WHERE `t`.published = 1
	                  AND `t`.quantity >= 0
	            GROUP BY `t`.id
	            ORDER BY `t`.id DESC
	        ";
        	}
        }
        
        $db->setQuery($query, $this->_limitstart, $this->_limit);
        $this->_items = $db->loadObjectList();
        
        return $this->_items;
    }
    
	function getTotal($id = null){
		// Initialise variables.
		$db        = $this->getDbo();
		$query    = $db->getQuery(true);
		$id = JRequest::getVar('id');
		$user = &JFactory::getUser();
		
		if($id == 'recommend'){
			$user_point = $_SESSION[$user->id.'p'];
			 
			$query = "
	            SELECT
	                `f`.NAME       AS `image`,
	                `t`.*
	            FROM #__wrd_products `t`
	                LEFT JOIN #__wrd_file `f`
	                  ON `f`.TYPE = 'image2'
	                    AND `t`.id = `f`.product_id
	            WHERE `t`.published = 1
	                  AND `t`.quantity > 0
	                  AND ((point <= ".$user_point." AND point > 0) OR (pointx <= ".$user_point." AND pointx > 0))
	            GROUP BY `t`.id
	            ORDER BY `t`.id DESC";
		}
		else{
			if($id != 0 ){
				$query = "
		            SELECT
		                `f`.NAME       AS `image`,
		                `t`.*
		            FROM #__wrd_products `t`
		                LEFT JOIN #__wrd_file `f`
		                  ON `f`.TYPE = 'image'
		                    AND `t`.id = `f`.product_id
		            WHERE `t`.published = 1
		                  AND `t`.quantity > 0
		                  AND `t`.cat_id = ".intval($_GET['id'])."
		            GROUP BY `t`.id
		            ORDER BY `t`.id DESC";
			}else{
				$query = "
		            SELECT
		                `f`.NAME       AS `image`,
		                `t`.*
		            FROM #__wrd_products `t`
		                LEFT JOIN #__wrd_file `f`
		                  ON `f`.TYPE = 'image2'
		                    AND `t`.id = `f`.product_id
		            WHERE `t`.published = 1
		                  AND `t`.quantity > 0
		            GROUP BY `t`.id
		            ORDER BY `t`.id DESC
		        ";
			}
		}

		$this->_total = $this->_getListCount($query);
		return $this->_total;
	}

	function getPagination(){
		
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->_limitstart, $this->_limit );
		}
		return $this->_pagination;
	}
	
	//function _buildQuery($user = null){
	//	return $query;
	//}
    
    public function getItemById(){
        // Initialise variables.
        $db        = $this->getDbo();
        $query    = $db->getQuery(true);
        $id = JRequest::getCmd('id', 0);
        
        /******** Basic Query ********/
        $query = "
            SELECT
                `f`.NAME AS `image`,
                `t`.*
            FROM #__wrd_products `t`
                LEFT JOIN #__wrd_file `f`
                  ON `f`.TYPE = 'image2'
                    AND `t`.id = `f`.product_id
            WHERE `t`.id = ".$id."
        ";
        //echo $query;
        $db->setQuery($query);
        $model = $db->loadObject();
        
        return $model;
    }
    
    public function getGallery(){
    	$mainframe = &JFactory::getApplication();
		$db        = $this->getDbo();
        $query    = $db->getQuery(true);
        $id = JRequest::getCmd('id', 0);
		if($id == ''){
			$mainframe->redirect("index.php?option=com_promotions&view=redemptions");
		}
		settype($id,"int");
		 /******** Basic Query ********/
        if($id != ''){
			$query = "
				SELECT
					`f`.NAME AS `image`,
					`t`.id 
				FROM #__wrd_products `t`
					LEFT JOIN #__wrd_file `f`
					  ON `f`.TYPE = 'image'
						AND `t`.id = `f`.product_id
				WHERE `t`.id = ".$id."
			";
		}
        $db->setQuery($query);
        $model = $db->loadObjectList();
        
        return $model;
    }
}
